#ifndef __ENGINE_REQUEST_SYNC_included
#define __ENGINE_REQUEST_SYNC_included

#include "Request.h"
#include "Device.h"
#include "VersionTag.h"
#include "DebugStream.h"

namespace Engine {

class CRequestSync : public CRequest {

public :

	CRequestSync(boost::asio::streambuf& data) :
		CRequest(string(COMMAND_SYNC), data)
	{
	}

	CRequestSync(CVersionTag& vt) :
		CRequest(string(COMMAND_SYNC))
	{
		JsonBuffer ss;
		JsonWriter writer(ss);

		writer.StartArray();
		vt.WriteJson(writer);
		writer.EndArray();

		SetContent(string(ss.GetString()), string(PACKAGE_CONTENT_TYPE_JSON));
	}

#ifdef SERVER
	virtual void DoRequest() {
		
		if(GetPropertieInt(string(PACKAGE_PROP_CONTENT_LENGTH)) == 0) {
			Response(RESPONSE_STATUS_OK);
			return;
		}

		boost::shared_ptr<JsonDocument> doc = ParseContentAsJson();

		if(!doc) {
			Response(RESPONSE_STATUS_BadRequest);
			return;
		}

		assert(doc->IsArray());
		for(int i = 0; i < doc->Size(); i++) {
			
			JsonValue& v = (*doc)[i];

			CVersionTag vt(v);
			if(vt.mTagName.length() == 0) continue;

			DebugStream << "CRequestSync::DoRequest() - sync ( " << vt.mTagName << ':' << vt.mVersion << ")\n";
			mDevice->SyncTag(vt);
		}

		Response(RESPONSE_STATUS_OK);
	}
#endif
};

}

#endif //__ENGINE_REQUEST_SYNC_included